package huanzhao.erp.util;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class AppContextUtil implements ApplicationContextAware {
    @Getter
    private static ApplicationContext applicationContext = null;

    /**
     * 通过name获取 Bean
     *
     * @param name Bean名称
     * @return Object
     * 2024/6/28 下午4:52:20
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean
     *
     * @param clazz Bean类
     * @return T
     * 2024/6/28 下午4:52:35
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name  Bean名称
     * @param clazz Bean类
     * @return T
     * 2024/6/28 下午4:52:43
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

    /**
     * 获取配置项
     *
     * @param key 配置项名称
     * @return String
     * 2024/1/6 11:58:24
     */
    public static String getProperty(String key) {
        Environment environment = getBean(Environment.class);
        return environment.getProperty(key);
    }

    /**
     * 获取配置项
     *
     * @param key   配置项名称
     * @param clazz 配置项类型
     * @param <T>   2024/1/7 13:33:12
     * @return T
     */
    public static <T> T getProperty(String key, Class<T> clazz) {
        Environment environment = getBean(Environment.class);
        return environment.getProperty(key, clazz);
    }

    /**
     * 重写接口的方法,该方法的参数为框架自动加载的IOC容器对象
     * 该方法在启动项目的时候会自动执行,前提是该类上有IOC相关注解,例如@Component
     *
     * @param applicationContext ioc容器
     * @throws BeansException e
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 将框架加载的ioc赋值给全局静态ioc
        AppContextUtil.applicationContext = applicationContext;
    }
}